/**
 * Created by spatra on 14-12-21.
 */

define(['markdownEditorJS/module', 'bootstrapMarkdown', 'markdownJs', 'markdownConverterJS', 'markdownSanitizerJS'],
  function(mdEditorModule){

    /**
     * angular指令，实现Markdown编辑器的预览功能
     *
     * 范例：
     *  <div markdown-previewer bind-content="content"></div>
     *
     */
    mdEditorModule.directive('markdownPreviewer', ['$window', '$sce',
      function($window, $sce){

        var converter = $window.Markdown.getSanitizingConverter();

        return {
          template: "<div ng-bind-html='sanitisedHtml' />",
          restrict: 'EA',
          replace: true,
          scope: {
            contentInMd: '=bindContent' ,
            class: '='
          },
          link: function(scope) {
            scope.$watch('contentInMd', function(value) {
              if (value !== undefined && value !== '') {
                scope.html = converter.makeHtml(value);
                scope.sanitisedHtml = $sce.trustAsHtml(scope.html);
              }
            });
          }
        };
    }]);//End of --> markdownPreviewer

    /**
     * angular指令，实现对Markdown编辑器进行配置和初始化
     *
     * 范例：
     *  [1]
     *  <textarea  ng-model="message.content" placeholder="请输入私信内容" markdown-editor>
     *  [2]: 需要隐藏指定的按钮（按钮命名参考：http://toopay.github.io/bootstrap-markdown/）
     *  <textarea
     *    ng-model="message.content"
     *    placeholder="请输入私信内容"
     *    markdownHiddenButtons＝"需要隐藏的按钮１，需要隐藏的按钮２"
     *    markdown-editor>
     */
    mdEditorModule.directive('markdownEditor', ['$window', function($window){

      /**
       * Markdown编辑器的本地化语言配置
       */
      $window.jQuery.fn.markdown.messages['zh'] = {
        'Bold': '加粗',
        'Italic': '斜体',
        'Preview': '预览',
        'Heading': '标题',
        'emphasized text': '强调',
        'Image': '图片',
        'Unordered List': '无序列表',
        'Ordered List': '有序列表',
        'Code': '代码',
        'Quote': '引用',
        'URL/Link': '链接'
      };

      return {
        restrict: 'EA',
        replace: false,
        scope: {
          markdownHiddenButtons: '@markdownHiddenButtons'
        },
        link: function(scope, element, attrs) {
          var hiddenButtons = scope.markdownHiddenButtons ? scope.markdownHiddenButtons.split(',') : [];

          //启动Bootstrap-Markdown
          element.markdown({
            hiddenButtons: hiddenButtons,
            language: 'zh'
          });
        }
      };
    }]);//End of --> markdownEditor

    /**
     * angular指令，去除文本中的一些特殊字符和Markdown的语法标记，便于预览
     *
     * 范例：
     *   <div markdown-extractor bind-content="content"></div>
     */
    mdEditorModule.directive('markdownExtractor', ['$sce',
      function($sce){

        //设置解析Markdown的正则表达式
        var regString = /[#*`>]+/g;

        var extract = function(scope, markdownText, regString) {
          if ( markdownText !== undefined ) {
            //确保为文本类型
            markdownText += '';console.log(markdownText);

            //使用javascript的正则表达式去除一些特殊字符和Markdown的语法标记
            scope.html = markdownText.replace(regString, ' ');
            scope.sanitisedHtml = $sce.trustAsHtml(scope.html);
          }
        };

      return {
        template: "<div ng-bind-html='sanitisedHtml' />",
        restrict: 'EA',
        replace: true,
        scope: {
          contentInPre: '=bindContent'
        },
        link: function (scope) {
          //监听变化，重新渲染
          scope.$watch('contentInPre', function (value) {
            extract(scope, value, regString);
          });
        }
      };
    }]);//End of --> markdownExtractor


});
